package club.kynb.mall.application.flow.order;

import club.kynb.mall.application.context.MallUserContext;
import club.kynb.mall.application.context.OrderPreviewContext;
import club.kynb.mall.application.model.model.vo.OrderPreviewResultVO;
import club.kynb.mall.user.api.IShippingAddressService;
import club.kynb.mall.user.model.dto.ShippingAddressDTO;
import cn.hutool.core.collection.CollectionUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.pizza.constant.GlobalConstant;
import org.pizza.pattern.filter.Filter;
import org.pizza.pattern.filter.FilterInvoker;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * @author kynb_club@163.com
 * @since 2021/7/5 9:02 下午
 */
@Slf4j
@Component
@AllArgsConstructor
public class DefaultShippingAddressFilter implements Filter<OrderPreviewContext> {
    private final IShippingAddressService iShippingAddressService;

    @Override
    public void doFilter(OrderPreviewContext orderPreviewContext, FilterInvoker<OrderPreviewContext> filterInvoker) {
        log.info("默认收货地址过滤器 start");
        final MallUserContext mallUserContext = MallUserContext.get(true);
        final List<ShippingAddressDTO> dtoList = iShippingAddressService.addressList(mallUserContext.getUserDTO().getId());
        orderPreviewContext.setShippingAddressList(dtoList);
        if (CollectionUtil.isNotEmpty(dtoList)) {
            final OrderPreviewResultVO orderPreviewResultVO = orderPreviewContext.getOrderPreviewResultVO();
            orderPreviewResultVO.setShippingAddressList(dtoList);
            final Optional<ShippingAddressDTO> optional = dtoList.stream().filter(addressDTO -> addressDTO.getDefaulted().equals(GlobalConstant.YES)).findFirst();
            if (optional.isPresent()) {
                orderPreviewResultVO.setDefaultShippingAddress(optional.get());
            } else {
                //最后创建的地址
                final Optional<ShippingAddressDTO> first = dtoList.stream().max(Comparator.comparing(ShippingAddressDTO::getId));
                first.ifPresent(orderPreviewResultVO::setDefaultShippingAddress);
            }
        }
        log.info("默认收货地址过滤器 end");
        filterInvoker.invoke(orderPreviewContext);
    }
}
